package com.swotxu.oldwebproject.utils;

import com.swotxu.oldwebproject.web.pojo.ConcurrentUser;
import com.swotxu.oldwebproject.web.pojo.UserInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * session 相关操作
 *
 * @Date: 2019/12/18 0018 12:31
 * @Author: swotXu
 */
public class SessionUtil {
    private static final Logger log = LoggerFactory.getLogger(SessionUtil.class);
    public final static String KEY_USERINFO = "USERINFO";

    public static void refreshSession(HttpServletRequest request){
        HttpSession oldSession = request.getSession(false);

        if (oldSession == null || oldSession.isNew()){
            log.info("concurrent session isNew!");
            return;
        }
        log.info("oldSession:{}", oldSession.getId());

        Map<String, Object> attrMap = new HashMap<>();
        // copy原session数据
        Enumeration<String> names = oldSession.getAttributeNames();
        while (names.hasMoreElements()){
            String key = names.nextElement();
            attrMap.put(key, oldSession.getAttribute(key));
        }
        // 注销原session前，清空 userinfo对象
        oldSession.removeAttribute(KEY_USERINFO);
        // 注销原session，触发 SessionListen
        oldSession.invalidate();
        // 创建获取新 session
        HttpSession newSession = request.getSession(true);
        log.info("newSession:{}", newSession.getId());

        Iterator<String> iterator = attrMap.keySet().iterator();
        while (iterator.hasNext()){
            String key = iterator.next();
            newSession.setAttribute(key, attrMap.get(key));
        }
        // 更新 userinfo对象记录
        UserInfo userInfo = ConcurrentUser.get();
        if (userInfo != null){
            userInfo.setToken(newSession.getId());
        }
    }
}
